package com.appbee.core.client.editors;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.HasEditorErrors;
import com.google.gwt.editor.client.IsEditor;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.safehtml.client.HasSafeHtml;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHTML;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LabelTextbox extends Composite implements
		IsEditor<LeafValueEditor<String>>,HasHTML,HasSafeHtml,HasEditorErrors<String>
{

	private static LabelTextboxUiBinder uiBinder = GWT
			.create(LabelTextboxUiBinder.class);

	interface LabelTextboxUiBinder extends UiBinder<Widget, LabelTextbox>
	{
	}

	@Ignore
	@UiField
	Element label;

	@Ignore
	@UiField
	TextBox textBox;
	
	@UiField
	Element msg;

	public LabelTextbox()
	{
		initWidget(uiBinder.createAndBindUi(this));
	}

	public LabelTextbox(String labelText)
	{
		this();
		label.setInnerText(labelText);
	}

	public LabelTextbox(SafeHtml labelText)
	{
		this();
		label.setInnerText(labelText.asString());
	}

	@Override
	public LeafValueEditor<String> asEditor()
	{
		return textBox.asEditor();
	}
	
	@Override
	public void setHTML(SafeHtml html)
	{
		label.setInnerHTML(html.asString());
	}

	@Override
	public void setHTML(String html)
	{
		label.setInnerText(html);
	}
	
	@Override
	public String getHTML()
	{
		return label.getInnerHTML();
	}
	
	@Override
	public void setText(String text)
	{
		label.setInnerText(text);
	}
	
	@Override
	public String getText()
	{
		return label.getInnerText();
	}
	
	public void addKeyUpHandler(KeyUpHandler handler)
	{
		textBox.addKeyUpHandler(handler);
	}
	public void addKeyDownHandler(KeyDownHandler handler)
	{
		textBox.addKeyDownHandler(handler);
	}
	
	public String getValue()
	{
		return textBox.getValue();
	}
	
	public void setValue(String value)
	{
		textBox.setValue(value);
	}
	
	@Override
	public void showErrors(List<EditorError> errors)
	{
		SafeHtmlBuilder sb = new SafeHtmlBuilder();
		for (EditorError editorError : errors)
		{
			sb.append(SafeHtmlUtils.fromString(editorError.getMessage()));
			sb.appendHtmlConstant("<br>");
			editorError.setConsumed(true);
		}
		msg.setInnerHTML(sb.toSafeHtml().asString());
		
	}
	
	public void setFocus(boolean focused)
	{
		textBox.setFocus(focused);
	}

}
